﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.IO;

namespace OnSpaceSI
{
    internal static class LicenseFiler
    {
        private static string apppathstring = null;
        private static string datapathstring = null;

        internal static bool LicenseAcceptancePresent(string argNamespace)
        {
            if (apppathstring == null || datapathstring == null) { GeneratePaths(argNamespace); }
            if (File.Exists(datapathstring)) { return CheckLARFile(datapathstring); }
            if (File.Exists(apppathstring)) { return CheckLARFile(apppathstring); }
            return false;
        }
        private static bool CheckLARFile(string argFilename)
        {
            StreamReader sr = new StreamReader(argFilename);
            string filecontents = sr.ReadToEnd();
            sr.Close();
            try
            {
                DateTime testdatetime = DateTime.Parse(filecontents);
                if (testdatetime.Ticks < DateTime.Now.Ticks)
                {
                    return true;
                }
            }
            catch { }
            return false;
        }
        private static void GeneratePaths(string argNamespace)
        {
            //'.LAR' for License Acceptance Record
            string workstring = argNamespace + ".LAR";
            apppathstring = Assembly.GetExecutingAssembly().Location;
            apppathstring = Path.Combine(Path.GetDirectoryName(apppathstring), workstring);
            string datapathstring = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            datapathstring = Path.Combine(datapathstring, argNamespace);
            datapathstring = Path.Combine(datapathstring, workstring);
        }
        internal static bool SaveLicenseAcceptance(string argNamespace)
        {
            if (apppathstring == null || datapathstring == null) { GeneratePaths(argNamespace); }
            try
            { SaveLicenseAcceptanceToFile(datapathstring); }
            catch
            {
                try { SaveLicenseAcceptanceToFile(apppathstring);  }
                catch { return false; }
            }
            return true;
        }
        private static void SaveLicenseAcceptanceToFile(string argFilename)
        {
            StreamWriter sw = new StreamWriter(argFilename, false);
            sw.Write(DateTime.Now.ToShortDateString());
            sw.Close();
        }
    }
}
